package com.yunwaikeji.gy_tool_library.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.yunwaikeji.gy_tool_library.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class GYChecked extends LinearLayout {
    public GYChecked(Context context) {
        super(context);
    }

    public GYChecked(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public GYChecked(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    @SuppressLint("NewApi")
    public GYChecked(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs);
    }

    private TextView textView(String text) {
        TextView textView = new TextView(getContext());
        textView.setGravity(Gravity.CENTER);
        textView.setText(text);
        textView.setPadding(Math.round(textPaddingLeft), Math.round(textPaddingTop), Math.round(textPaddingRight), Math.round(textPaddingBottom));
        textView.setTextSize(px2sp(getContext(), textSize));
        if (isFull) {
            textView.setLayoutParams(new LayoutParams(0, MATCH_PARENT, 1));
        } else {
            textView.setLayoutParams(new LayoutParams(Math.round(checkWidth), Math.round(checkHeight)));
        }
//        textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
        textView.setSingleLine(true);
//        checkHeight = textView.getHeight();
//        Log.v("test","===="+checkHeight);
//        if (dividerHeight==0){
//            dividerHeight = checkHeight;
//        }
        return textView;
    }

    private int noCheckedColor;
    private int checkedColor;
    private float itemRadius;
    private int noCheckedTextColor;
    private int checkedTextColor;
    private float textSize;

    private int prohibitCheckedColor;
    private int prohibitCheckedTextColor;
    private float prohibitCheckedEdgeWidth;
    private int prohibitCheckedEdgeColor;
    //是否多选
    private boolean isMultipleSelection;
    //是否可以取消最后一个
    private boolean isCancelLast;
    private float checkWidth;
    private float checkHeight;

    private float checkedEdgeWidth;
    private int checkedEdgeColor;

    private float noCheckedEdgeWidth;
    private int noCheckedEdgeColor;

    private float horizontalSpacing;
    private int horizontalSpacingColor;

    private float dividerWidth;
    private float dividerHeight;
    private int dividerColor;
    private boolean isFull;

    private float textPaddingLeft;
    private float textPaddingRight;
    private float textPaddingTop;
    private float textPaddingBottom;
    private float textPadding;

    private List<String> contentList = new ArrayList<>();
    private List<Integer> checkedList = new ArrayList<>();
    private List<Integer> noCheckedList = new ArrayList<>();

    private int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT;
    private int MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT;

    private void init(AttributeSet attributeSet) {
        TypedArray typedArray = getContext().obtainStyledAttributes(attributeSet, R.styleable.GYChecked);
        noCheckedColor = typedArray.getColor(R.styleable.GYChecked_noCheckedColor, Color.parseColor("#F2F2F2"));
        noCheckedTextColor = typedArray.getColor(R.styleable.GYChecked_noCheckedTextColor, Color.parseColor("#292929"));
        checkedColor = typedArray.getColor(R.styleable.GYChecked_checkedColor, Color.parseColor("#DCDCDC"));
        checkedTextColor = typedArray.getColor(R.styleable.GYChecked_checkedTextColor, Color.parseColor("#292929"));
        itemRadius = typedArray.getDimension(R.styleable.GYChecked_itemRadius, 0);
        textSize = typedArray.getDimension(R.styleable.GYChecked_textSize, sp2px(getContext(), 14));
        textPadding = typedArray.getDimension(R.styleable.GYChecked_textPadding, 0);
        textPaddingLeft = typedArray.getDimension(R.styleable.GYChecked_textPaddingLeft, 0);
        textPaddingRight = typedArray.getDimension(R.styleable.GYChecked_textPaddingRight, 0);
        textPaddingTop = typedArray.getDimension(R.styleable.GYChecked_textPaddingTop, 0);
        textPaddingBottom = typedArray.getDimension(R.styleable.GYChecked_textPaddingBottom, 0);
        isMultipleSelection = typedArray.getBoolean(R.styleable.GYChecked_isMultipleSelection, false);
        isCancelLast = typedArray.getBoolean(R.styleable.GYChecked_isCancelLast, false);
        checkWidth = typedArray.getDimension(R.styleable.GYChecked_checkWidth, WRAP_CONTENT);
        checkHeight = typedArray.getDimension(R.styleable.GYChecked_checkHeight, WRAP_CONTENT);
        horizontalSpacing = typedArray.getDimension(R.styleable.GYChecked_horizontalSpacing, 0);
        noCheckedEdgeWidth = typedArray.getDimension(R.styleable.GYChecked_noCheckedEdgeWidth, 0);
        noCheckedEdgeColor = typedArray.getColor(R.styleable.GYChecked_noCheckedEdgeColor, Color.parseColor("#AAAAAA"));
        checkedEdgeWidth = typedArray.getDimension(R.styleable.GYChecked_checkedEdgeWidth, 0);
        checkedEdgeColor = typedArray.getColor(R.styleable.GYChecked_checkedEdgeColor, Color.parseColor("#AAAAAA"));
        horizontalSpacingColor = typedArray.getColor(R.styleable.GYChecked_horizontalSpacingColor, Color.TRANSPARENT);
        dividerWidth = typedArray.getDimension(R.styleable.GYChecked_dividerWidth, 0);
        dividerHeight = typedArray.getDimension(R.styleable.GYChecked_dividerHeight, MATCH_PARENT);
        dividerColor = typedArray.getColor(R.styleable.GYChecked_dividerColor, Color.TRANSPARENT);
        isFull = typedArray.getBoolean(R.styleable.GYChecked_isFull, false);
        prohibitCheckedColor = typedArray.getColor(R.styleable.GYChecked_prohibitCheckedColor, Color.parseColor("#FFFFFF"));
        prohibitCheckedTextColor = typedArray.getColor(R.styleable.GYChecked_prohibitCheckedTextColor, Color.parseColor("#DDDDDD"));
        prohibitCheckedEdgeWidth = typedArray.getDimension(R.styleable.GYChecked_prohibitCheckedEdgeWidth, 0);
        prohibitCheckedEdgeColor = typedArray.getColor(R.styleable.GYChecked_prohibitCheckedEdgeColor, Color.parseColor("#AAAAAA"));

        init();
    }

    public void setStrings(String... strings) {
        setStrings(Arrays.asList(strings));
    }

    public void setStrings(List<String> stringList) {
        contentList.clear();
        contentList.addAll(stringList);
        checkedList.clear();
        noCheckedList.clear();
        initView();
    }

    public void setDefault(Integer... integers) {
        setDefault(Arrays.asList(integers));
    }

    public List<Integer> getNoChecked() {
        return noCheckedList;
    }

    public List<Integer> getDefault() {
        return checkedList;
    }

    public void setNoChecked(Integer... integers) {
        setNoChecked(Arrays.asList(integers));
    }

    public void setNoChecked(List<Integer> integerList) {
        Collections.sort(integerList);
        noCheckedList.clear();
        noCheckedList.addAll(integerList);
        for (int i : noCheckedList) {
            if (i < textViewList.size()) {
                setCheckedTextViewType(textViewList.get(i), 3);
            }
        }
    }

    public void setDefault(List<Integer> integerList) {
        Collections.sort(integerList);
        checkedList.clear();
        checkedList.addAll(integerList);
        for (int i = 0;i<textViewList.size();i++){
            if (!noCheckedList.contains(i)){
                setCheckedTextViewType(textViewList.get(i), 2);
                if (isMultipleSelection){
                    if (checkedList.contains(i)){
                        setCheckedTextViewType(textViewList.get(i), 1);
                    }
                }else {
                    if (checkedList.size()>0 && checkedList.get(checkedList.size()-1) == i){
                        setCheckedTextViewType(textViewList.get(i), 1);
                    }
                }
            }
        }
    }

    /**
     * 是否可以多选
     *
     * @param isMultipleSelection
     */
    public void setIsMultipleSelection(boolean isMultipleSelection) {
        this.isMultipleSelection = isMultipleSelection;
    }

    /**
     * 是否允许取消最后一个
     *
     * @param isCancelLast
     */
    public void setIsCancelLast(boolean isCancelLast) {
        this.isCancelLast = isCancelLast;
    }

    //=============================================================================================
    List<TextView> textViewList = new ArrayList<>();
    LinearLayout linearLayout = new LinearLayout(getContext());

    private void init() {
        if (textPadding > 0) {
            textPaddingLeft = textPadding;
            textPaddingTop = textPadding;
            textPaddingRight = textPadding;
            textPaddingBottom = textPadding;
        }
        if (horizontalSpacing < dividerWidth) {
            horizontalSpacing = dividerWidth;
        }
        setGravity(Gravity.CENTER);
        setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setGravity(Gravity.CENTER);
//        linearLayout.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

        setStrings("item1", "item2", "item3");
        setDefault(0);
        setNoChecked(2);
    }

    private void initView() {
        removeAllViews();
        linearLayout.removeAllViews();
        textViewList.clear();
        if (isFull) {
            linearLayout.setLayoutParams(new LayoutParams(MATCH_PARENT, MATCH_PARENT));
        } else {
            linearLayout.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
        }
        for (int i = 0; i < contentList.size(); i++) {
            TextView textView = textView(contentList.get(i));
            setCheckedTextViewType(textView, 2);
            final int finalI = i;
            textView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    //点击
                    if (noCheckedList.contains(finalI)) {
                        if (onNoCheckedListener != null) {
                            onNoCheckedListener.onNoChecked(finalI);
                        }
                        if (onCheckedClickListener != null) {
                            onCheckedClickListener.onNoChecked(finalI);
                        }
                        return;
                    }
                    initListener(finalI);
                }
            });
            linearLayout.addView(textView);
            textViewList.add(textView);
            if (contentList.size() > 1 && i < contentList.size() - 1) {
                linearLayout.addView(betweenView());
            }
        }
        addView(linearLayout);
    }

    private void initListener(int i) {
        int type = 1;
        //点击
        if (isMultipleSelection) {
            //多选
            if (checkedList.contains(i)) {
                if (checkedList.size() == 1) {
                    if (isCancelLast) {
                        checkedList.clear();
                        type = 2;
                    }
                } else {
                    for (int j = 0; j < checkedList.size(); j++) {
                        if (i == checkedList.get(j)) {
                            checkedList.remove(j);
                        }
                    }
                    type = 2;
                }
            } else {
                checkedList.add(i);
                type = 1;
            }
        } else {
            //单选
            if (checkedList.contains(i)) {
                if (isCancelLast) {
                    checkedList.clear();
                    type = 2;
                }
            } else {
                for (int j = 0;j<textViewList.size();j++){
                    if (!noCheckedList.contains(j)){
                        setCheckedTextViewType(textViewList.get(j), 2);
                    }
                }
                checkedList.clear();
                checkedList.add(i);
                type = 1;
            }
        }
        setCheckedTextViewType(textViewList.get(i), type);
        Collections.sort(checkedList);
        if (onCheckedListener != null) {
            if (type == 1) {
                onCheckedListener.onChecked(checkedList, i, true);
            } else if (type == 2) {
                onCheckedListener.onChecked(checkedList, i, false);
            }
        }
        if (onCheckedClickListener != null) {
            if (type == 1) {
                onCheckedClickListener.onChecked(checkedList, i, true);
            } else if (type == 2) {
                onCheckedClickListener.onChecked(checkedList, i, false);
            }
        }
    }

    private LinearLayout betweenView() {
        LinearLayout linearLayout = new LinearLayout(getContext());
        linearLayout.setGravity(Gravity.CENTER);
        linearLayout.setLayoutParams(new LayoutParams(Math.round(horizontalSpacing), Math.round(dividerHeight)));
        linearLayout.setBackgroundColor(horizontalSpacingColor);
        View view = new View(getContext());
        view.setBackgroundColor(horizontalSpacingColor);
        view.setLayoutParams(new LayoutParams(Math.round(dividerWidth), Math.round(dividerHeight)));
        view.setBackgroundColor(dividerColor);
        linearLayout.addView(view);
        return linearLayout;
    }

    private void setCheckedTextViewType(TextView textView, int type) {
        switch (type) {
            case 1:
                //选中
                textView.setTextColor(checkedTextColor);
                textView.setBackgroundDrawable(getDrawable(checkedColor, Math.round(checkedEdgeWidth), checkedEdgeColor, Math.round(itemRadius)));
                break;
            case 2:
                //未选中
                textView.setTextColor(noCheckedTextColor);
                textView.setBackgroundDrawable(getDrawable(noCheckedColor, Math.round(noCheckedEdgeWidth), noCheckedEdgeColor, Math.round(itemRadius)));
                break;
            case 3:
                //禁止选择
                textView.setTextColor(prohibitCheckedTextColor);
                textView.setBackgroundDrawable(getDrawable(prohibitCheckedColor, Math.round(prohibitCheckedEdgeWidth), prohibitCheckedEdgeColor, Math.round(itemRadius)));
                break;
        }
    }
    //=============================================================================================

    public void setOnCheckedListener(OnCheckedListener onCheckedListener) {
        this.onCheckedListener = onCheckedListener;
    }

    private OnCheckedListener onCheckedListener;

    public interface OnCheckedListener {
        void onChecked(List<Integer> integerList, int checkedId, boolean isChecked);
    }

    public void setOnCheckedClickListener(OnCheckedClickListener onCheckedClickListener) {
        this.onCheckedClickListener = onCheckedClickListener;
    }

    private OnCheckedClickListener onCheckedClickListener;

    public interface OnCheckedClickListener {
        void onChecked(List<Integer> integerList, int checkedId, boolean isChecked);

        void onNoChecked(int checkedId);
    }

    public void setOnNoCheckedListener(OnNoCheckedListener onNoCheckedListener) {
        this.onNoCheckedListener = onNoCheckedListener;
    }

    private OnNoCheckedListener onNoCheckedListener;

    public interface OnNoCheckedListener {
        void onNoChecked(int checkedId);
    }

    /**
     * 添加背景色、圆角、边框/颜色
     *
     * @param backgroundColor 背景色
     * @param strokeWidth     边框宽
     * @param strokeColor     边框颜色
     * @param radius          圆角度
     */
    private GradientDrawable getDrawable(int backgroundColor, int strokeWidth, int strokeColor, int radius) {
        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setStroke(strokeWidth, strokeColor);
        if (radius != 0) {
            gradientDrawable.setCornerRadius(radius);
        }
        gradientDrawable.setColor(backgroundColor);
        return gradientDrawable;
    }

    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param context
     * @param pxValue （DisplayMetrics类中属性density）
     * @return
     */
    private int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param context
     * @param dipValue （DisplayMetrics类中属性density）
     * @return
     */
    private int dp2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param context
     * @param pxValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    private int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param context
     * @param spValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    private int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        this.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
            }
        });
    }
}
